package org.andao.commons.taglib.loader;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

import org.andao.commons.taglib.BaseTagSupport;
import org.andao.core.support.context.SpringContextHolder;
import org.andao.core.utils.ExStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.util.StringSplitUtils;




/**
 * 组件文件加载标签.<p>
 * 
 * @author Marco.hu(hzg139@163.com)
 */
public class ResourceFileLoaderTag extends BaseTagSupport {

	private static final long serialVersionUID = 6446159387285277219L;
	
	private static Logger logger = LoggerFactory.getLogger(ResourceFileLoaderTag.class);
	
	/**组件列表，用逗号分隔符分开 比如："treeView,gridView,tabView" */
	private String components;
	
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();	
				
		ResourceFileLoader loadComponentsFile = SpringContextHolder.getBean("loadComponentsFile");;
		StringBuilder html = new StringBuilder();
		String[] cs = StringSplitUtils.splitIgnoringQuotes(components, ',');
		String idString = "";
		for(String c : cs){
			// 根据组件代码获取文件列表
			List<ResourceFile> cfs = loadComponentsFile.getComponentsFiles(c);
			for(ResourceFile cf : cfs){
				if(!ExStringUtils.isEmpty(cf.getFileId())){
					idString = " id= '" + cf.getFileId() +" '";
				}
				if(cf.getFileType().equals(ResourceFile.fileType_Js)){
					html.append("<script type=\"text/javascript\" "+idString+" src=\""+getBaseUrl()+cf.getFilePath()+"\"></script>\n");
				}
				if(cf.getFileType().equals(ResourceFile.fileType_Css)){
					html.append("<link rel=\"stylesheet\" "+idString+" href=\""+getBaseUrl()+cf.getFilePath()+"\" />\n");
				}
				if(cf.getFileType().equals(ResourceFile.fileType_lang)){					
					String language = request.getLocale().getLanguage();
					String cfPath = getBaseUrl()+cf.getFilePath()+"."+language+".js";
					File cfFile = new File(request.getRealPath(cf.getFilePath()+"."+language+".js"));
					if(!cfFile.exists()){
						cfPath = getBaseUrl()+cf.getFilePath()+".zh.js";
					}
					html.append("<script type=\"text/javascript\" "+idString+" src=\""+cfPath+"\"></script>\n");
					logger.debug("use lang :"+cfPath);
				}
			}
		}
		try {
			pageContext.getOut().print(html.toString());
		} catch (IOException e) {		
			logger.error(e.getMessage());
		}
		return super.doStartTag();
	}

	public String getComponents() {
		return components;
	}

	public void setComponents(String components) {
		this.components = components;
	}
	
}

